package com.tougutips.common.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.tougutips.common.core.constant.TokenConstants;

import java.util.Date;
import java.util.Map;

public final class JWTUtil {
    public static String sign(Map<String,Object> userInfo) {
        // 签名算法
        Algorithm algorithm = Algorithm.HMAC256(TokenConstants.SECRET);
        // 过期时间
        Date expering_time = new Date(System.currentTimeMillis() + TokenConstants.EXPERING_TIME);
        String token = JWT.create()
                // 创建payload
                .withClaim(TokenConstants.PAYLOAD, userInfo)
                //过期时间
                .withExpiresAt(expering_time)
                .sign(algorithm);
        return token;
    }

    public static boolean verify(String token) {
        // 签名算法
        Algorithm algorithm = Algorithm.HMAC256(TokenConstants.SECRET);
        // 比较两个Token是否一样
        JWTVerifier jwtVerifier = JWT
                .require(algorithm)
                .build();
        jwtVerifier.verify(token);
        return true;
    }

    public static Map<String,Object> getAccount(String token) {
        DecodedJWT decode = JWT.decode(token);
        return decode.getClaim(TokenConstants.PAYLOAD).asMap();
    }
}
